<template>
  <!-- <Dialog :title="dialogTitle" :fullscreen="'true'" v-model="dialogVisible"> -->
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="学生姓名" prop="studentName">
        <el-input v-model.trim="formData.studentName" placeholder="请输入学生姓名" />
      </el-form-item>
      <el-form-item label="学籍号" prop="studentCode">
        <el-input
          v-model.trim="formData.studentCode"
          placeholder="请输入学籍号"
          @blur="fillSort()"
        />
      </el-form-item>

      <el-form-item label="身份证号" prop="idNumber">
        <el-input v-model.trim="formData.idNumber" placeholder="请输入身份证号" />
      </el-form-item>

      <el-form-item label="学生编号" prop="sort">
        <el-input v-model.trim="formData.sort" placeholder="学生编号" />
      </el-form-item>
      <el-form-item label="口令" prop="openId">
        <el-input v-model.trim="formData.openId" placeholder="请输入口令" />
      </el-form-item>
      <el-form-item label="照片">
        <UploadImg v-model="formData.pictureUrl" :limit="1" :updateUrl="updateUrl" />
      </el-form-item>
      <cascadeSelection
        ref="selection"
        :useType="true"
        :schoolType="schoolType"
        @school-register="getSchoolRegisterInfo"
      />

      <el-form-item label="性别" prop="sex">
        <el-select v-model.trim="formData.sex" placeholder="请选择">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="年级" prop="grade">
        <el-select v-model="formData.grade" placeholder="请选择" :disabled="true">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CMIS_GRADE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="在校状态" prop="state">
        <el-select v-model="formData.state" placeholder="请选择">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CMIS_STUDENT_STATE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model.trim="formData.mobile" placeholder="请输入手机号" maxLength="50" />
      </el-form-item>

      <el-collapse>
        <el-collapse-item>
          <el-form-item label="档案创建时间" prop="archivesCreateTime">
            <el-date-picker
              v-model="formData.archivesCreateTime"
              type="date"
              value-format="x"
              placeholder="选择档案创建时间"
            />
          </el-form-item>
          <el-form-item label="档案编号" prop="archivesCode">
            <el-input
              v-model.trim="formData.archivesCode"
              placeholder="请输入档案编号"
              maxLength="50"
            />
          </el-form-item>
          <el-form-item label="注册时间" prop="enrollmentTime">
            <el-date-picker
              v-model="formData.enrollmentTime"
              type="date"
              value-format="x"
              placeholder="选择注册时间"
            />
          </el-form-item>
          <el-form-item label="年级名称" prop="gradeName">
            <el-input
              v-model.trim="formData.gradeName"
              placeholder="请输入年级名称"
              maxLength="50"
            />
          </el-form-item>
          <el-form-item label="身份证号码" prop="idNumber">
            <el-input
              v-model.trim="formData.idNumber"
              placeholder="请输入身份证号码"
              maxLength="50"
            />
          </el-form-item>
          <el-form-item label="卡号" prop="cardNumber">
            <el-input v-model.trim="formData.cardNumber" placeholder="请输入卡号" maxLength="50" />
          </el-form-item>
          <el-form-item label="民族" prop="nation">
            <el-input v-model.trim="formData.nation" placeholder="请输入民族" maxLength="50" />
          </el-form-item>
          <!--      <el-form-item label="是否有照片" prop="picture">-->
          <!--        <el-input-->
          <!--          v-model.trim="formData.picture"-->
          <!--          placeholder="请输入是否有照片"-->
          <!--          maxLength="50"-->
          <!--        />-->
          <!--      </el-form-item>-->
          <!--      <el-form-item label="照片URL" prop="pictureUrl">-->
          <!--        <el-input v-model.trim="formData.pictureUrl" placeholder="请输入照片URL" maxLength="50" />-->
          <!--      </el-form-item>-->
          <el-form-item label="出生日期" prop="birthday">
            <el-input
              v-model.trim="formData.birthday"
              placeholder="请输入出生日期"
              maxLength="50"
            />
          </el-form-item>
          <el-form-item label="学生来源" prop="studentSource">
            <el-input
              v-model.trim="formData.studentSource"
              placeholder="请输入学生来源"
              maxLength="50"
            />
          </el-form-item>
          <el-form-item label="家庭住址" prop="homeAddress">
            <el-input
              v-model.trim="formData.homeAddress"
              placeholder="请输入家庭住址"
              maxLength="50"
            />
          </el-form-item>
          <el-form-item label="毕业高中" prop="highSchool">
            <el-input
              v-model.trim="formData.highSchool"
              placeholder="请输入毕业高中"
              maxLength="50"
            />
          </el-form-item>
          <!--      <el-form-item label="学籍号" prop="studentNumber">-->
          <!--        <el-input v-model.trim="formData.studentNumber" placeholder="请输入学籍号" maxLength="50" />-->
          <!--      </el-form-item>-->
          <el-form-item label="届(入学年份)" prop="entryYear">
            <el-input
              v-model.trim="formData.entryYear"
              placeholder="请输入届(入学年份)"
              maxLength="50"
            />
          </el-form-item>
          <el-form-item label="毕业时间" prop="graduationTime">
            <el-date-picker
              v-model="formData.graduationTime"
              type="date"
              value-format="x"
              placeholder="选择毕业时间"
            />
          </el-form-item>
          <el-form-item label="离校时间" prop="departureTime">
            <el-date-picker
              v-model="formData.departureTime"
              type="date"
              value-format="x"
              placeholder="选择离校时间"
            />
          </el-form-item>
          <el-form-item label="离校原因" prop="departureReason">
            <el-input
              v-model.trim="formData.departureReason"
              placeholder="请输入离校原因"
              maxLength="50"
            />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model.trim="formData.email" placeholder="请输入邮箱" maxLength="50" />
          </el-form-item>
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as StudentApi from '@/api/cmis/student'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const infoType = ref(true) // 编辑时隐藏下拉状态
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const schoolType = ref(false) //是否禁用学校
const updateUrl = ref(
  import.meta.env.VITE_BASE_URL + '/admin-api/cmis/student/upload-student-photo'
) //上传地址
const formData = ref({
  id: undefined,
  studentName: undefined,
  studentCode: undefined,
  sex: undefined,
  grade: undefined,
  deptId: undefined,
  state: undefined,
  archivesCreateTime: undefined,
  archivesCode: undefined,
  enrollmentTime: undefined,
  gradeName: undefined,
  idNumber: undefined,
  cardNumber: undefined,
  nation: undefined,
  picture: undefined,
  pictureUrl: undefined,
  birthday: undefined,
  studentSource: undefined,
  homeAddress: undefined,
  highSchool: undefined,
  sort: undefined,
  studentNumber: undefined,
  entryYear: undefined,
  graduationTime: undefined,
  departureTime: undefined,
  departureReason: undefined,
  userId: undefined,
  mobile: undefined,
  email: undefined,
  openId: undefined
})
const formRules = reactive({
  studentName: [{ required: true, message: '学生姓名不能为空', trigger: 'blur' }],
  studentCode: [{ required: true, message: '学籍号不能为空', trigger: 'blur' }],
  schoolId: [{ required: true, message: '学校id不能为空', trigger: 'blur' }],
  // collegeId: [{ required: true, message: '机构id不能为空', trigger: 'blur' }],
  classesId: [{ required: true, message: '班级不能为空', trigger: 'blur' }],
  sex: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
  grade: [{ required: true, message: '年级不能为空,请检查当前班级是否存在年级', trigger: 'blur' }],
  mobile: [
    {
      required: false,
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  schoolType.value = false

  resetForm()
  // 修改时，设置数据
  if (id) {
    schoolType.value = true
    formLoading.value = true
    try {
      const res = await StudentApi.getStudent(id)
      formData.value = res
      // 触发赋值后传值
      selection.value.getAllList(res)

      infoType.value = false
    } finally {
      formLoading.value = false
    }
  } else {
    infoType.value = true
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 接收子组件的数据
const selection = ref()

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  const selectData = { ...selection.value.selectData }

  formData.value = Object.assign(formData.value, selectData)

  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as StudentApi.StudentVO
    if (formType.value === 'create') {
      await StudentApi.createStudent(data)
      message.success(t('common.createSuccess'))
    } else {
      await StudentApi.updateStudent(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

//获取年级
const getSchoolRegisterInfo = (data) => {
  formData.value.grade = data.grade
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    studentName: undefined,
    studentCode: undefined,
    sex: undefined,
    grade: undefined,
    deptId: undefined,
    state: 1, //默认值 在校
    archivesCreateTime: undefined,
    archivesCode: undefined,
    enrollmentTime: undefined,
    gradeName: undefined,
    idNumber: undefined,
    cardNumber: undefined,
    nation: undefined,
    picture: undefined,
    pictureUrl: undefined,
    birthday: undefined,
    studentSource: undefined,
    homeAddress: undefined,
    highSchool: undefined,
    sort: undefined,
    studentNumber: undefined,
    entryYear: undefined,
    graduationTime: undefined,
    departureTime: undefined,
    departureReason: undefined,
    userId: undefined,
    mobile: undefined,
    email: undefined,
    openId: undefined
  }
  selection.value = undefined

  formRef.value?.resetFields()
}

const fillSort = () => {
  if (!formData.value.sort) {
    formData.value.sort = formData.value.studentCode
  }
}
</script>
